﻿using EasyModbus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zhy.EasyModbusTCP
{
    /// <summary>
    /// Modbus客户端操作类
    /// </summary>
    public class ModbusClientWrapper
    {
        /// <summary>
        /// Modbus客户端实例
        /// </summary>
        private ModbusClient modbusClient;
        /// <summary>
        /// Modbus TCP 服务器地址
        /// </summary>
        string ipAddress = "127.0.0.1"; // 修改为你的 Modbus TCP 服务器的 IP 地址
        /// <summary>
        /// Modbus TCP 的默认端口是 502
        /// </summary>
        int port = 502; // 
        /// <summary>
        /// Modbus 设备单元标识符，根据你的设备设置
        /// </summary>
        byte unitIdentifier = 1; // 

        public ModbusClientWrapper() 
        {
            
        }

        /// <summary>
        /// 初始化客户端
        /// </summary>
        public ModbusClientWrapper(string _ipAddress, int _port, byte _unitIdentifier) :base()
        {
            ipAddress = _ipAddress;
            port = _port;
            unitIdentifier = _unitIdentifier;
        }

        /// <summary>
        /// 链接
        /// </summary>
        public void Connect()
        {
            modbusClient = new ModbusClient(ipAddress, port); // IP地址端口号
            modbusClient.UnitIdentifier = unitIdentifier; // 从站地址
            modbusClient.Connect();
        }

        /// <summary>
        /// 断开链接
        /// </summary>
        public void Disconnect()
        {
            modbusClient.Disconnect();
        }

        /// <summary>
        /// 读取保持寄存器
        /// </summary>
        /// <param name="startAddress">读取地址</param>
        /// <param name="quantity">读取数量</param>
        /// <returns></returns>
        public int[] ReadHoldingRegisters(byte startAddress, byte quantity)
        {
            return modbusClient.ReadHoldingRegisters(startAddress, quantity);
        }

        /// <summary>
        /// 写入保持寄存器
        /// </summary>
        /// <param name="startAddress">写入地址</param>
        /// <param name="value">写入值</param>
        public void WriteHoldingRegister(byte startAddress, byte value)
        {
            // 向保持寄存器（例如，地址为1的寄存器）写入value值
            modbusClient.WriteSingleRegister(startAddress, value); // 将地址为1的寄存器的值设置为1234
        }
    }
}
